﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Tools.Collections;

namespace Tools.Collections
{
    /// <summary>
    /// 2011-06-15 by 杜有发
    /// </summary>
    public class KeyedQueue<TKey,TValue>
    {
        Dictionary<TKey, ThreadSafeQueue<TValue>> _dict = new Dictionary<TKey, ThreadSafeQueue<TValue>>();

        /// <summary>
        /// 
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public void Add(TKey key, TValue value)
        {
            MakeSureExists(key);

            ThreadSafeQueue<TValue> q = _dict[key];
            q.Enqueue(value);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="key"></param>
        /// <param name="values"></param>
        public void AddAll(TKey key, IEnumerable<TValue> values)
        {
            MakeSureExists(key);

            ThreadSafeQueue<TValue> q = _dict[key];
            q.EnqueueAll(values);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public List<TValue> GetAll(TKey key)
        {
            MakeSureExists(key);

            return _dict[key].DequeueAll();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public List<TKey> GetAllKeys()
        {
            return _dict.Keys.ToList();
        }

        /// <summary>
        /// 确保存在
        /// </summary>
        /// <param name="key"></param>
        void MakeSureExists(TKey key)
        {
            if (!_dict.ContainsKey(key))
            {
                lock (_dict)
                {
                    if (!_dict.ContainsKey(key))
                        _dict.Add(key, new ThreadSafeQueue<TValue>());
                }
            }
        }
    }
}
